import { UserConfig,ConfigEnv,loadEnv } from "vite"
import pluginEnv from "vite-plugin-vue-env"
import vue from "@vitejs/plugin-vue"
// 下载按需加载的插件 vite-plugin-style-import,一个自动导入组件库样式的vite插件
import styleImport from "vite-plugin-style-import"
// 需要引入@types/node，否则无法找到path路径
import path from "path"


const setAlias = (alias:string[][]) => {
  return alias.map(v => {
    return { find:v[0], replacement: path.resolve(__dirname,v[1]) }
  })
}

export default ({ command, mode }:ConfigEnv): UserConfig => {
  // const root = process.cwd()
  // const env = loadEnv(mode, root)
  // console.log(command, env)
  // base:loadEnv(mode, process.cwd()).VITE_APP_NAME, 解决无法使用import.meta.env.*的办法
  return {
    base: "./",// 在生产中服务时的基本公共路径。@default '/' 
    resolve:{
      alias:setAlias([
        ["/@","src"]
      ])
    },
    server:{
      port:8080,
      hmr:{
        host:"172.31.24.47",
        port:8080
      },
      proxy:{
        "/api": {
          target:"http://172.31.24.47:8080/",
          changeOrigin: false,
          rewrite: (path) => path.replace(/^\/api/, "")
        }
      }
    },
    plugins:[
      vue(),
      pluginEnv({
        VUE_ENV: "development"
      }),
      styleImport({
        libs:[
          {
            libraryName:"element-plus",
            esModule:true,
            ensureStyleFile: true, // 忽略文件是否存在, 导入不存在的CSS文件时防止错误。
            resolveStyle:(name:string) => {
              return `element-plus/lib/theme-chalk/${name}.css`
            }
          }
        ]
      })
    ],
    css:{
      preprocessorOptions:{
        less:{
          modifyVars: {
            hack: `true; @import (reference) "${path.resolve("src/styles/index.less")}";`
          },
          javascriptEnabled: true
        }
      }
    },
    build: {
      // 生产环境移除 console
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      }
    }
    // 引入第三方的配置
    //   optimizeDeps: {
    //     include: ["moment", "echarts", "axios", "mockjs"],
    //   },
  }
}
  

